package com.digitalchina.lxnsy.activity.management;

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.activity.old.WebViewActivity;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.FarmOptStatVO;
import com.digitalchina.lxnsy.entity.FarmRecordVarietyVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.OkHttpUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.xml.AdminXML;
import com.digitalchina.lxnsy.xml.UserXML;
import com.lzy.okhttputils.model.HttpParams;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity.management
 * 创建人：郑皓
 * 创建时间：2019/7/12 10:35
 * 修改备注：
 * ================================================
 */
public class FarmingStatisticsActivity extends BaseActivity {
    @Bind(R.id.tv_date_start)
    TextView tvDateStart;
    @Bind(R.id.layout_date_start)
    RelativeLayout layoutDateStart;
    @Bind(R.id.tv_date_end)
    TextView tvDateEnd;
    @Bind(R.id.layout_date_end)
    RelativeLayout layoutDateEnd;
    @Bind(R.id.rb_1)
    RadioButton rb1;
    @Bind(R.id.rb_2)
    RadioButton rb2;
    @Bind(R.id.radioGroup)
    RadioGroup radioGroup;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.layout_name)
    RelativeLayout layoutName;
    @Bind(R.id.tv_operation)
    TextView tvOperation;
    @Bind(R.id.layout_operation)
    RelativeLayout layoutOperation;
    @Bind(R.id.bt_search)
    Button btSearch;
    @Bind(R.id.layout_search)
    LinearLayout layoutSearch;

    private int mYear;
    private int mMonth;
    private int mDayOfMonth;

    //作物
    private List<FarmRecordVarietyVO> cropList = new ArrayList<>();
    //操作
    private List<FarmRecordVarietyVO> optList = new ArrayList<>();


    private OptionsPickerView pvCrop, pvOpt;

    private String cropId = ""; // 作物ID
    private String farmOperationId = ""; //操作ID

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_farming_statistics);
        setTitle("农事统计");
    }

    @Override
    public void initMember() {
        Calendar calendar = Calendar.getInstance();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);

        getData();
    }

    @Override
    public void addListener() {


        // 单选器
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (radioGroup.getCheckedRadioButtonId() == R.id.rb_1) {
                    layoutName.setVisibility(View.GONE);
                    layoutOperation.setVisibility(View.GONE);
                    layoutSearch.setVisibility(View.GONE);
                } else {
                    layoutName.setVisibility(View.VISIBLE);
                    layoutOperation.setVisibility(View.VISIBLE);
                }
            }
        });

    }

    @Override
    public void setHandler() {
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                switch (message.what) {
                    case MSG_S_0:
                        callBack(message.obj);
                        break;
                    case MSG_F_0:
                        showToast(message.obj.toString());
                        break;
                    case MSG_S_1:
                        setData(message.obj);
                        break;
                    case MSG_F_1:
                        showToast(message.obj.toString());
                        break;
                }
                return false;
            }
        });
    }

    @Override
    public void callBack(Object object) {

        cropList = FastJsonUtil.getListBean(object.toString(), "cropInfoSelectVOS", FarmRecordVarietyVO.class);
        optList = FastJsonUtil.getListBean(object.toString(), "farmOperationSelectVOS", FarmRecordVarietyVO.class);


        pvCrop = new OptionsPickerView.Builder(activity, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                String select = cropList.get(options1).getName();
                cropId = cropList.get(options1).getId();
                tvName.setText(select);
            }
        })
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();
        pvCrop.setPicker(cropList);


        pvOpt = new OptionsPickerView.Builder(activity, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                String select = optList.get(options1).getName();
                farmOperationId = optList.get(options1).getId();
                tvOperation.setText(select);
            }
        })
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();
        pvOpt.setPicker(optList);
    }

    //展示底部数据
    public void setData(Object object) {

        List<FarmOptStatVO> list = FastJsonUtil.getListBean(object.toString(), "farmOperationStatVOS", FarmOptStatVO.class);


        if (list != null && list.size() > 0) {
            layoutSearch.removeAllViews();
            layoutSearch.setVisibility(View.VISIBLE);
            for (int i = 0; i < list.size(); i++) {
                View view = LayoutInflater.from(activity).inflate(R.layout.view_msg_details, layoutSearch, false);
                TextView tvKey = view.findViewById(R.id.tv_key);
                TextView tvValue = view.findViewById(R.id.tv_value);
                tvKey.setText(list.get(i).getName());
                tvValue.setText(list.get(i).getValue());
                layoutSearch.addView(view);
            }

        } else {
            layoutSearch.setVisibility(View.GONE);
            showToast("暂无查询数据");
        }

    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.layout_date_start, R.id.layout_date_end, R.id.layout_name, R.id.layout_operation, R.id.bt_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_date_start:
                showDatePicker(0);
                break;
            case R.id.layout_date_end:
                showDatePicker(1);
                break;
            case R.id.layout_name:
                if (pvCrop != null)
                    pvCrop.show();
                break;
            case R.id.layout_operation:
                if (pvOpt != null)
                    pvOpt.show();
                break;
            case R.id.bt_search:
                search();
                break;
        }
    }


    private void showDatePicker(final int i) {
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
                String date = year + "-" + (month + 1) + "-" + dayOfMonth;
                if (i == 0)
                    tvDateStart.setText(date);
                else
                    tvDateEnd.setText(date);
            }
        }, mYear, mMonth, mDayOfMonth);

        datePickerDialog.show();
    }

    private void getData() {

        HttpParams params = new HttpParams();
        params.put("enterpriseId", AdminXML.getEnterpriseId(activity));
        params.put("resNo", AdminXML.getResNo(activity));

        OkHttpUtil.post(activity, URL.URL_GET_FARM_STAT_BASE_DATA, "", params, mHandler,
                MSG_S_0, MSG_F_0);
    }

    //查询
    private void search() {

        String startTime = tvDateStart.getText().toString();
        String endTime = tvDateEnd.getText().toString();

        if (StringUtil.isStrEmpty(startTime)) {
            showToast("请选择开始日期");
            return;
        }

        if (StringUtil.isStrEmpty(endTime)) {
            showToast("请选择结束日期");
            return;
        }


        if (radioGroup.getCheckedRadioButtonId() == R.id.rb_1) {
            //跳转页面
            Map<String, String> map = new HashMap<>();
            map.put("url", getUrl());
            map.put("title", "农事统计");
            GotoUtil.gotoActivity(activity, WebViewActivity.class,"map",map);
        } else {

            if (StringUtil.isStrEmpty(cropId)) {
                showToast("请选择作物名称");
                return;
            }

            if (StringUtil.isStrEmpty(farmOperationId)) {
                showToast("请选择农事操作");
                return;
            }

            HttpParams params = new HttpParams();
            params.put("enterpriseId", AdminXML.getEnterpriseId(activity));
            params.put("resNo", AdminXML.getResNo(activity));
            params.put("startTime", startTime);
            params.put("endTime", endTime);
            params.put("cropId", cropId);
            params.put("farmOperationId", farmOperationId);

            OkHttpUtil.post(activity, URL.URL_FARM_OPERATION_STAT, "正在查询...", params, mHandler,
                    MSG_S_1, MSG_F_1);
        }

    }

    private String getUrl() {

        String url = URL.URL_FARM_OPERATION_H5 +
                "?enterpriseId=" + AdminXML.getEnterpriseId(activity) +
                "&resNo=" + AdminXML.getResNo(activity) +
                "&LOGIN=" + UserXML.getLOGIN(activity) +
                "&startTime=" + tvDateStart.getText().toString() +
                "&endTime=" + tvDateEnd.getText().toString();

        return url;

    }


}
